# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2020/2/11 17:11
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : parase.py
# @Software   : PyCharm
# -----------------------------------------

import os
from configparser import ConfigParser


class ParseConf:
    def __init__(self, path):
        if not os.path.exists(path):
            return None
        self.parse = ConfigParser()
        self.parse.read(path)

    def get_section_options(self, section):
        """获取配置文件内section的options"""
        return self.parse.options(section)

    def check_option(self, section, option):
        """检查是否存在option"""
        if not self.check_section(section):
            return False
        if option in self.get_section_options(section):
            return True
        else:
            return False

    def get_sections(self):
        """获取配置文件内sections"""
        return self.parse.sections()

    def check_section(self, section):
        """检查指定的section是否存在"""
        if section in self.get_sections():
            return True
        else:
            return False

    def get_section_info(self, section):
        """
        获取section的key=value
        default section的值会被获取到，被作为默认值
        如果指定的section不存在，返回{}；否则返回key,value
        """
        section_info = {}
        if self.check_section('default'):
            default_options = self.get_section_options('default')
            for option in default_options:
                section_info[option] = self.parse.get('default', option)
        if section == 'default':
            return section_info
        if self.check_section(section):
            section_options = self.get_section_options(section)
            for option in section_options:
                section_info[option] = self.parse.get(section, option)
        else:
            return {}
        return section_info

    def get_sections_info(self):
        """获取所有sections info，section:{key=value}"""
        sections = self.get_sections()
        sections_info = {}
        for section in sections:
            sections_info[section] = self.get_section_info(section)
        return sections_info
